package com.costeaalex.datedrivenfilecopy.model.erasers;

/**
 * @author Alex Costea
 * 
 * Class that handles erasing operations over FTP.
 * 
 */

import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import com.costeaalex.datedrivenfilecopy.model.interfaces.IEraser;

public class FTPEraser implements IEraser {
	
	private String[] connectionData;
	private FTPClient FTPC;
	
	public FTPEraser(String[] connectionData) {
		this.connectionData=connectionData;
	}
	
	@Override
	public void init() {
		FTPC=new FTPClient();
		try {
			FTPC.connect(connectionData[0]);
			FTPC.login(connectionData[1], connectionData[2]);
		}
		catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	@Override
	public boolean delete(EraseFile file) {
		try {
			if(file.isDirectory())
				FTPC.removeDirectory(file.getStringPath());
			else
				FTPC.deleteFile(file.getStringPath());
			return true;
		}
		catch(Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}

	@Override
	public void destroy() {
		if(FTPC!=null)
			try {
				FTPC.logout();
				FTPC.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	@Override
	public ArrayList<EraseFile> getFileList(EraseFile file) {
		try {
			FTPFile[] files=FTPC.listFiles(file.getStringPath());
			FTPFile[] dirs=FTPC.listDirectories(file.getStringPath());
			ArrayList<EraseFile> aL=new ArrayList<EraseFile>();
			
			for(int i=0; i<files.length; i++)
				aL.add(new EraseFile(file.getStringPath()+"/"+files[i].getName(), false));
			for(int i=0; i<dirs.length; i++)
				aL.add(new EraseFile(file.getStringPath()+"/"+dirs[i].getName(), true));
	
			return aL;
		}
		catch(Exception e) {
			
		}
		return null;
	}

}
